package bean;

import Interfaces.StudentImpl;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author: android 超级兵
 * @create: 2022-01-17 16:58
 * TODO
 **/
public class StudentBean2 implements StudentImpl {
    private String name = "";
    private int age = 0;
    private final ReadWriteLock lock =
            new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();


    @Override
    public String getName() throws InterruptedException {
        readLock.lock();
        try {
            // sleep 5ms 模拟网络请求
            Thread.sleep(5);
            return name;
        } finally {
            readLock.unlock();
        }
    }

    @Override
    public int getAge() throws InterruptedException {
        readLock.lock();
        try {
            // sleep 5ms 模拟网络请求
            Thread.sleep(5);
            return age;
        } finally {
            readLock.unlock();
        }
    }

    @Override
    public void setName(String name) throws InterruptedException {
        writeLock.lock();
        try {
            // sleep 5ms 模拟网络请求
            Thread.sleep(5);
            this.name = name;
        } finally {
            writeLock.unlock();
        }
    }

    @Override
    public void setAge(int age) throws InterruptedException {
        writeLock.lock();
        try {
            // sleep 5ms 模拟网络请求
            Thread.sleep(5);
            this.age = age;
        } finally {
            writeLock.unlock();
        }
    }
}
